<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:doctor:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:doctor:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:doctor:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:doctor:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="doctorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="55" />
      <el-table-column label="姓名" align="center" prop="name" width="160"/>
      <el-table-column label="头像" align="center" prop="avator" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.avator" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="tel" width="110"/>
      <el-table-column label="性别" align="center" prop="sex">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center" prop="introduction" width="200"/>
      <el-table-column label="擅长" align="center" prop="good" width="200"/>
      <el-table-column label="签约人数" align="center" prop="sign" width="80" />
      <el-table-column label="邮箱" align="center" prop="email" width="200"/>
      <el-table-column label="ruoyiId" align="center" prop="sysUserId">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sysUserId"/>
        </template>
      </el-table-column>
      <el-table-column label="评分" align="center" prop="rating" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createuser" />
      <el-table-column label="状态:0:正常1禁用" align="center" prop="state">
        <template #default="scope">
          <dict-tag :options="sys_common_status" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="扩展1" align="center" prop="exp1" />
      <el-table-column label="扩展2" align="center" prop="exp2" />
      <el-table-column label="扩展3" align="center" prop="exp3" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:doctor:edit']">修改</el-button>
<!--          <el-tooltip content="重置密码" placement="top" v-if="scope.row.userId !== 1">-->
            <el-button link type="primary" icon="Key" @click="handleReset(scope.row)" v-hasPermi="['system:user:resetPwd']"></el-button>
<!--          </el-tooltip>-->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:doctor:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医生管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="doctorRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item v-if="title =='添加医生管理'" label="用户密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="头像" prop="avator">
          <image-upload v-model="form.avator"/>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别:数据字典">
            <el-option
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input v-model="form.introduction" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="擅长" prop="good">
          <el-input v-model="form.good" placeholder="请输入擅长" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="状态:0:正常1禁用" prop="state">
          <el-select v-model="form.state" placeholder="请选择状态:0:正常1禁用">
            <el-option
              v-for="dict in sys_common_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Doctor">
import { listDoctor, getDoctor, delDoctor, addDoctor, updateDoctor } from "@/api/system/doctor";
import {parseTime} from "@/utils/ruoyi.js";
import useUserStore from "@/store/modules/user.js";
import {getUser, addUser, resetUserPwd, updateUser} from "@/api/system/user";


const { proxy } = getCurrentInstance();
const { sys_common_status, sys_user_sex } = proxy.useDict('sys_common_status', 'sys_user_sex');
const user = useUserStore()
const doctorList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
//查看管理员模板信息
let gly=ref({});
gly.value = {
  userId: undefined,
  deptId: undefined,
  userName: undefined,
  nickName: undefined,
  password: undefined,
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  status: "0",
  remark: undefined,
  postIds: [],
  roleIds: []
};
//查看管理员模板信息
const  glyxxi=()=> {
  getUser(107).then(response => {
    console.log("response", response)
    gly.value = response.data;
    gly.value.password = undefined;
    gly.value.userId = undefined;
    gly.value.userName = undefined;
    gly.value.phonenumber = undefined;
    gly.value.email = undefined;
  })
}
  glyxxi();
//添加管理员和医生信息
  const addxx = () => {
    gly.value.userName = form.value.name;
    gly.value.phonenumber = form.value.tel;//电话
    gly.value.sex = form.value.sex;//性别
    gly.value.email = form.value.email;//邮箱
    gly.value.password = form.value.password;//密码
    gly.value.nickName = form.value.name;//昵称
    // console.log("gly",gly)
    addUser(gly.value).then(response => {//添加管理员信息
      if (response.code == 200) {
        form.value.sysUserId = response.data;
        //添加医生信息
        addDoctor(form.value).then(response => {
          if (response.code == 200) {
            proxy.$message.success("操作成功");
            open.value = false;
            getList();
          }
        })
      }
    })
  }
//修改管理员和医生信息
  const updatexx = () => {
    gly.value.userName = form.value.name;
    gly.value.phonenumber = form.value.tel;//电话
    gly.value.sex = form.value.sex;//性别
    gly.value.email = form.value.email;//邮箱
    gly.value.nickName = form.value.name;//昵称
    gly.value.userId = form.value.sysUserId;
    // console.log("gly",gly)
    updateUser(gly.value).then(response => {//修改管理员信息
            updateDoctor(form.value).then(response => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
            });
        }
    )
  }


  function handleReset(row) {
    proxy.$prompt('请输入"' + row.name + '"的新密码', "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      inputPattern: /^.{5,20}$/,
      inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      inputValidator: (value) => {
        if (/<|>|"|'|\||\\/.test(value)) {
          return "不能包含非法字符：< > \" ' \\\ |"
        }
      },
    }).then(({value}) => {
      resetUserPwd(row.sysUserId, value)
      .then(response => {
        proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
      });
    })
        .catch(() => {
    });
  }


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
  },
  rules: {
    userName: [{ required: true, message: "用户名称不能为空", trigger: "blur" }, { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" }],
    nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
    password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }, { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }, { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    tel: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询医生管理列表 */
function getList() {
  loading.value = true;
  listDoctor(queryParams.value).then(response => {
    doctorList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    console.log(doctorList.value)
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    avator: null,
    tel: null,
    sex: null,
    introduction: null,
    good: null,
    sign: 0,
    email: null,
    sysUserId: null,
    rating: 0.0,
    createtime: null,
    createuser: null,
    state: null,
    del: null,
    exp1: null,
    exp2: null,
    exp3: null
  };
  proxy.resetForm("doctorRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加医生管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDoctor(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改医生管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["doctorRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        form.value.createtime=parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}");
        updatexx();
      } else {
        addxx();
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除医生管理编号为"' + _ids + '"的数据项？').then(function() {
    return delDoctor(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/doctor/export', {
    ...queryParams.value
  }, `doctor_${new Date().getTime()}.xlsx`)
}

getList();
</script>
